package com.business.user.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.business.common.constant.MessageConstant;
import com.business.common.enums.BusinessExceptionEnum;
import com.business.common.enums.ErrorEnum;
import com.business.common.exception.BusinessException;
import com.business.common.exception.CustomException;
import com.business.common.utils.FileUploadUtil;
import com.business.common.utils.StrKit;
import com.business.redis.ExpiresTimeEnum;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisUtil;
import com.business.user.entity.Message;
import com.business.user.entity.UserDetails;
import com.business.user.mapper.UserDetailsMapper;
import com.business.user.rabbitMq.RabbitMqSender;
import com.business.user.service.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 用户详细信息表:业务接口实现类
 *
 * @author chenjiehong
 * @date 2019-12-03 10:07:51
 * @since 1.0
 */
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDetailsMapper userDetailsMapper;

    @Autowired
    private RabbitMqSender rabbitMqSender;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 获取信息完整度
     *
     * @return
     */
    private int getInfoDegree(UserDetails userDetails) {
        int degree = 60;
        //简介
        if (StrKit.isNotEmpty(userDetails.getSynopsis())) {
            degree += 10;
        }
        //职位 公司
        if (StrKit.isNotEmpty(userDetails.getProfession()) && StrKit.isNotEmpty(userDetails.getCompany())) {
            degree += 10;
        }
        //标签
        if (StrKit.isNotEmpty(userDetails.getTags())) {
            degree += 10;
        }
        //名片
        if (StrKit.isNotEmpty(userDetails.getCardUrl())) {
            degree += 10;
        }

        return degree;
    }

    public UserDetails add(UserDetails userDetails) {
        if (userDetails.getUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId");
        }
        if (userDetails.getSex() != null && (userDetails.getSex() != 0 && userDetails.getSex() != 1)) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "sex");
        }
        userDetails.setCreateTime(new Date());
        userDetails.setType(0);
        userDetails.setExpireTime(null);
        userDetails.setHeadUrl(null);
        //设置信息完整度
        userDetails.setDegree(getInfoDegree(userDetails));
        Integer r = userDetailsMapper.insert(userDetails);
        if (r != null && r > 0) {
            //发送系统消息
            Message message = new Message();
            message.setUserId(userDetails.getUserId());
            message.setFromUserId(1);//系统用户
            message.setType(0);
            //调整到赠送页面
            message.setDetailsUrl("/member-gift?userId=" + userDetails.getUserId());
            message.setContent(String.format(MessageConstant.USER_DETAILS_ADD, userDetails.getRealName(), "2019-12-01", "2020-03-01"));
            rabbitMqSender.addMessage(message);
            return userDetails;
        } else {
            throw new BusinessException(BusinessExceptionEnum.USER_INSERT_FAIL);
        }
    }

    /**
     * 用户详情修改
     *
     * @param userDetails
     * @return
     */
    @Override
    @Transactional
    public UserDetails update(UserDetails userDetails) {
        if (userDetails.getUserId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId");
        }
        if (userDetails.getSex() != null && (userDetails.getSex() != 0 && userDetails.getSex() != 1)) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "sex");
        }
        Integer count = userDetailsMapper.selectCount(new EntityWrapper<UserDetails>().eq("user_id", userDetails.getUserId()));
        if (count == null || count == 0) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "userId 不正确");
        }
        userDetails.setUpdateTime(new Date());
        userDetails.setType(null);
        userDetails.setExpireTime(null);
        userDetails.setCreateTime(null);
        userDetails.setHeadUrl(null);
        //设置信息完整度
        userDetails.setDegree(getInfoDegree(userDetails));
        Integer r = userDetailsMapper.updateById(userDetails);
        if (r != null && r > 0) {
            return userDetails;
        } else {
            throw new BusinessException(BusinessExceptionEnum.USER_UPDATE_FAIL);
        }
    }

    private String getAllUrl(String url) {
        if (StrKit.isNotEmpty(url)) {
            return fileUploadUtil.getUrl(url);
        }
        return null;

    }

    @Override
    public UserDetails query(Integer id) {
        String key = String.format(RedisKeyConstant.USER_DETAILS_QUERY_USER, id);
        if (RedisUtil.hasKey(key)) {
            return (UserDetails) RedisUtil.getObject(key, UserDetails.class);
        } else {
            UserDetails userDetails = userDetailsMapper.selectById(id);
            userDetails.setCardUrl(getAllUrl(userDetails.getCardUrl()));
            userDetails.setHeadUrl(getAllUrl(userDetails.getHeadUrl()));
            if (userDetails != null) {
                RedisUtil.setValue(key, userDetails, ExpiresTimeEnum.LOGIN.getExpiresTime());
            } else {
                throw new BusinessException(BusinessExceptionEnum.USER_NON_EXIST);
            }
            return userDetails;
        }
    }

    @Override
    public Map<String, Object> queryName(Integer id) {
        Wrapper<UserDetails> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("user_id as userId,real_name as realName,head_url as headUrl,type").eq("user_id", id);
        List<Map<String, Object>> list = userDetailsMapper.selectMaps(wrapper);
        if (list != null && list.size() > 0) {
            list.forEach(stringObjectMap -> {
                stringObjectMap.put("headUrl",getAllUrl(stringObjectMap.get("headUrl")+""));
            });
            return list.get(0);
        }
        throw new BusinessException(BusinessExceptionEnum.USER_NON_EXIST);
    }

    @Override
    public List<Map<String, Object>> queryNameList(List<Integer> ids) {
        Wrapper<UserDetails> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("user_id as userId,real_name as realName,head_url as headUrl,type").in("user_id", ids);
        List<Map<String, Object>> list = userDetailsMapper.selectMaps(wrapper);
        if (list != null && list.size() > 0) {
            list.forEach(stringObjectMap -> {
                stringObjectMap.put("headUrl",getAllUrl(stringObjectMap.get("headUrl")+""));
            });
            return list;
        }
        throw new BusinessException(BusinessExceptionEnum.USER_NON_EXIST);
    }

    /**
     * 修改
     *
     * @param id              用户id
     * @param newHeadImageUrl 新头像地址
     * @return 返回旧地址，如果不是默认头像
     */
    @Override
    @Transactional
    public String updateHeadImage(int id, String newHeadImageUrl) {
        String headUrl = userDetailsMapper.getHeadUrl(id);
        UserDetails userDetails = new UserDetails();
        userDetails.setUserId(id);
        userDetails.setHeadUrl(newHeadImageUrl);
        userDetails.setUpdateTime(new Date());
        int i = userDetailsMapper.updateById(userDetails);
        if (i > 0) {
            return headUrl;
        } else {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "id 不正确");
        }
    }


    /**
     * 修改
     *
     * @param id         用户id
     * @param newCardUrl 名片地址
     * @return 返回旧地址
     */
    @Override
    @Transactional
    public String updateCardUrl(int id, String newCardUrl) {
        UserDetails userDetails = userDetailsMapper.selectById(id);
        String url = userDetails.getCardUrl();
        userDetails.setUserId(id);
        userDetails.setCardUrl(newCardUrl);
        userDetails.setUpdateTime(new Date());
        userDetails.setDegree(getInfoDegree(userDetails));
        int i = userDetailsMapper.updateById(userDetails);
        if (i > 0) {
            return url;
        } else {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "id 不正确");
        }
    }

}